package com.ysd.util;

import cn.hutool.json.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/***
 *@title AESUtils
 *@author WH
 *@version 1.0.0
 *@create 2025/1/8 17:47
 **/
public class AESUtils {

    //定义key的常量
    private static final String KEY = "ysd1234567890qaz";
    private static final String IV = "qaz1234567890ysd";

    /**
     * 解密方法
     * @param encryptedText Base64编码的密文
     * @return 解密后的明文
     * @throws Exception 如果解密过程中发生错误
     */
    public static String decrypt(String encryptedText) throws Exception {
        // 创建AES密钥
        try {
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");

            // 创建初始化向量
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());

            // 创建Cipher实例并初始化为解密模式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

            // 解码Base64编码的密文
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);

            // 解密数据
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            String result = new String(decryptedBytes);
            JSONObject jsonObject = new JSONObject(result);
            String moduleCode = jsonObject.getStr("moduleCode");
            // 将解密后的字节数组转换为字符串
            return moduleCode;
        }catch (Exception e){
            return "";
        }

    }
}
